package com.wangjie.minio.service;

import com.wangjie.minio.autoconfigure.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class MinioService {
    private static final Logger logger = LoggerFactory.getLogger(MinioService.class);

    private final MinioClient minioClient;
    private final MinioProperties minioProperties;

    public MinioService(MinioClient minioClient, MinioProperties minioProperties) {
        this.minioClient = minioClient;
        this.minioProperties = minioProperties;
    }

    public String uploadFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("File cannot be null or empty");
        }
        return uploadFile(file.getInputStream(), file.getSize(), file.getOriginalFilename(), file.getContentType());
    }

    public String uploadFile(InputStream stream, long fileSize, String originalName, String contentType) throws Exception {
        String fileName = generateFileName(originalName);
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .contentType(contentType)
                    .stream(stream, fileSize, -1L)
                    .build());
        } catch (MinioException e) {
            logger.error("Minio error occurred while uploading file: {}", e.getMessage());
            throw new Exception("File upload failed: " + e.getMessage());
        }

        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
        logger.info("File uploaded successfully. Access URL: {}", url);

        return url;
    }

    private String generateFileName(String originalName) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
        String date = sdf.format(new Date());
        return date + "/" + uuid + "_" + originalName;
    }
}
